﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Core.Tools
{
    public class DictionaryEnumerator : IDictionaryEnumerator
    {
        private readonly Func<int, DictionaryEntry> GetValue;
        private int End;
        private int Begin;
        private int Index;
        private bool IsAsc;

        /// <summary>
        /// 指定范围初始化迭代器
        /// </summary>
        /// <param name="GetValue">获得值的函数</param>
        /// <param name="Begin">开始索引</param>
        /// <param name="End">结束索引</param>
        /// <param name="IsAsc">是否正序迭代</param>
        public DictionaryEnumerator(Func<int, DictionaryEntry> GetValue, int Begin, int End, bool IsAsc)
        {
            this.GetValue = GetValue;
            this.Begin = Begin;
            this.End = End;
            this.IsAsc = IsAsc;

            Reset();
        }
        /// <summary>
        /// 指定长度初始化迭代器
        /// </summary>
        /// <param name="GetValue">获得值的函数</param>
        /// <param name="Length">集合长度</param>
        /// <param name="IsAsc">是否正序迭代</param>
        public DictionaryEnumerator(Func<int, DictionaryEntry> GetValue, int Length, bool IsAsc) : this(GetValue, 0, Length - 1, IsAsc)
        {

        }

        public object Key { get { return Entry.Key; } }

        public object Value { get { return Entry.Value; } }

        public DictionaryEntry Entry
        {
            get
            {
                if (Index >= Begin && Index <= End)
                {
                    return GetValue(Index);
                }

                throw new IndexOutOfRangeException("Index");
            }
        }

        public object Current { get { return Entry; } }

        public bool MoveNext()
        {
            if (IsAsc)
            {
                try
                {
                    return Index < End;
                }
                finally
                {
                    ++Index;
                }

            }
            else
            {
                try
                {
                    return Index > Begin;
                }
                finally
                {
                    --Index;
                }
            }
        }

        public void Reset()
        {
            Index = IsAsc ? Begin - 1 : End + 1;
        }
    }
}
